﻿package kit4j.tests.jdk.swing;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class TestSwingConcurrentEvent {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JFrame mainFrame = createMainFrame();

		mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainFrame.pack();
		mainFrame.setLocationRelativeTo(null);
		mainFrame.setVisible(true);
	}

	static JFrame createMainFrame() {
		JFrame mainFrame = new JFrame();

		mainFrame.setLayout(new GridLayout(2, 1));
		mainFrame.add(createButton("btn1"));
		mainFrame.add(createButton("btn2"));

		return mainFrame;
	}

	static JButton createButton(String text) {
		JButton btn = new JButton(text);

		btn.addActionListener(createButtonActionListener(btn));

		return btn;
	}

	static ActionListener createButtonActionListener(final JButton btn) {
		ActionListener listener = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				SwingUtilities.invokeLater(new Runnable() {

					@Override
					public void run() {
						System.out.println("clicked btn:" + btn.getText());
						System.out.println("now sleep 5 seconds...");

						try {
							TimeUnit.SECONDS.sleep(5);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
					}

				});
			}
		};

		return listener;
	}

}
